const userApi = require("../../../api/user.js");
const asyncTools = require("../../../utils/asyncTools.js");
Page({
  data: {
    pageDataList: [],
    editorKey: 4,
    showPopBack: false,
    insertDir: "up",
    insertIdx: 0,
    userId: "",
    popImage: "",
    showPopBack3: false,
    popImgUrl: "",
    popItemIdx: "",
    popImgIdx: "",
    bottomPadding: "",
  },
  async onLoad() {
    this.setData({ userId: wx.getStorageSync("userInfo").id });
    this.setData({ bottomPadding: getApp().globalData.bottomPadding });
    wx.setNavigationBarTitle({
      title: "企业名片编辑",
    });
    let res = await userApi.getEnterpriseCard({
      userId: wx.getStorageSync("userInfo").id,
    });
    if (res.data) {
      this.setData({
        pageDataList: JSON.parse(res.data.enterpriseInfo),
      });
    }
  },
  async saveBusinessCard() {
    await userApi.getSignature().then(async (res) => {
      for (const item of this.data.pageDataList) {
        if (
          item.type === "img" ||
          item.type === "imgs" ||
          item.type === "video"
        ) {
          let tempContent = [];
          await this.upload(res.data, item.content, "list").then((res1) => {
            tempContent = res1;
          });
          item.content = tempContent;
        }
      }
    });
    let data = {
      enterpriseName: "企业名称",
      enterpriseInfo: JSON.stringify(this.data.pageDataList),
    };
    await userApi.saveEnterpriseCard(data).then(async (res) => {
      wx.showToast({
        title: "保存成功！",
        duration: 2000,
      });
      await asyncTools.delay(2000);
      wx.switchTab({ url: "/pages/user/index" });
    });
  },
  upload(ossConfig, data, type) {
    let tempList = [];
    let tempDataList = type === "list" ? data : [data];
    return new Promise((reslove, reject) => {
      for (let i = 0; i < tempDataList.length; i++) {
        if (tempDataList[i].indexOf("tmp") === -1) {
          tempList.push(tempDataList[i]);
          if (tempList.length === tempDataList.length) {
            if (type === "list") {
              reslove(tempList);
            } else {
              reslove(tempDataList[i]);
            }
          }
        } else {
          let fileName = "";
          if (tempDataList[i].indexOf("tmp/") !== -1) {
            fileName = tempDataList[i].split("tmp/")[1];
          } else if (tempDataList[i].indexOf("tmp") !== -1) {
            fileName = tempDataList[i].split("tmp")[1];
          } else {
            fileName = tempDataList[i];
          }
          wx.uploadFile({
            filePath: tempDataList[i],
            name: "file",
            url: ossConfig.host,
            formData: {
              name: tempDataList[i],
              key: ossConfig.dir + "/" + fileName,
              policy: ossConfig.policy,
              signature: ossConfig.signature,
              success_action_status: "200",
              OSSAccessKeyId: ossConfig.accessid,
            },
            success: function (res) {
              if (type === "list") {
                tempList.push(
                  ossConfig.host + "/" + ossConfig.dir + "/" + fileName
                );
                if (tempList.length === tempDataList.length) {
                  reslove(tempList);
                }
              } else {
                reslove(ossConfig.host + "/" + ossConfig.dir + "/" + fileName);
              }
            },
            fail: function (res) {},
          });
        }
      }
    });
  },
  deleteClick() {
    wx.navigateBack();
  },
  addEditorItem(e) {
    let type = e.currentTarget.dataset["type"];
    let insert = e.currentTarget.dataset["insert"];
    let that = this;
    this.data.editorKey =
      this.data.editorKey + 1 + this.data.pageDataList.length;
    let imgNum = 0;
    this.data.pageDataList.forEach((item) => {
      if (item.type.indexOf("img") !== -1) {
        imgNum++;
      }
    });
    switch (type) {
      case "img":
        if (imgNum < 9) {
          wx.chooseMedia({
            count: 1,
            mediaType: "image",
            success: function (e) {
              if (!insert) {
                that.data.pageDataList.push({
                  type,
                  content: [e.tempFiles[0].tempFilePath],
                  key: that.data.editorKey,
                });
              } else {
                that.data.pageDataList.splice(
                  that.data.insertDir === "up"
                    ? that.data.insertIdx
                    : that.data.insertIdx + 1,
                  0,
                  {
                    type,
                    content: [e.tempFiles[0].tempFilePath],
                    key: that.data.editorKey,
                  }
                );
              }
              that.setData({
                pageDataList: that.data.pageDataList,
              });
            },
          });
        } else {
          wx.showToast({
            title: "最多选择九组图片！",
            icon: "error",
            duration: 2000,
          });
        }
        break;

      case "imgs":
        if (imgNum < 9) {
          wx.chooseMedia({
            count: 9,
            mediaType: "image",
            success: function (e) {
              let tempList = [];
              e.tempFiles.forEach((item) => {
                tempList.push(item.tempFilePath);
              });
              if (!insert) {
                that.data.pageDataList.push({
                  type,
                  content: tempList,
                  key: that.data.editorKey,
                });
              } else {
                that.data.pageDataList.splice(
                  that.data.insertDir === "up"
                    ? that.data.insertIdx
                    : that.data.insertIdx + 1,
                  0,
                  {
                    type,
                    content: tempList,
                    key: that.data.editorKey,
                  }
                );
              }
              that.setData({
                pageDataList: that.data.pageDataList,
              });
            },
          });
        } else {
          wx.showToast({
            title: "最多选择九组图片！",
            icon: "error",
            duration: 2000,
          });
        }
        break;

      case "video":
        let hasVideo = this.data.pageDataList.find(
          (item) => item.type === "video"
        );
        if (!hasVideo) {
          wx.chooseMedia({
            count: 1,
            mediaType: "video",
            success: function (e) {
              if (!insert) {
                that.data.pageDataList.push({
                  type,
                  content: [e.tempFiles[0].tempFilePath],
                  key: that.data.editorKey,
                });
              } else {
                that.data.pageDataList.splice(
                  that.data.insertDir === "up"
                    ? that.data.insertIdx
                    : that.data.insertIdx + 1,
                  0,
                  {
                    type,
                    content: [e.tempFiles[0].tempFilePath],
                    key: that.data.editorKey,
                  }
                );
              }
              that.setData({
                pageDataList: that.data.pageDataList,
              });
            },
          });
        } else {
          wx.showToast({
            title: "最多选择一个视频！",
            icon: "error",
            duration: 2000,
          });
        }
        break;

      case "map":
        let hasMap = this.data.pageDataList.find((item) => item.type === "map");
        if (!hasMap) {
          wx.chooseLocation({
            success: function (res) {
              if (!insert) {
                that.data.pageDataList.push({
                  type,
                  latitude: res.latitude,
                  longitude: res.longitude,
                  markers: [
                    {
                      id: 1,
                      latitude: res.latitude,
                      longitude: res.longitude,
                      iconPath: "../../assets/location.png",
                    },
                  ],
                  key: that.data.editorKey,
                });
              } else {
                that.data.pageDataList.splice(
                  that.data.insertDir === "up"
                    ? that.data.insertIdx
                    : that.data.insertIdx + 1,
                  0,
                  {
                    type,
                    latitude: res.latitude,
                    longitude: res.longitude,
                    markers: [
                      {
                        id: 1,
                        latitude: res.latitude,
                        longitude: res.longitude,
                        iconPath: "../../assets/location.png",
                      },
                    ],
                    key: that.data.editorKey,
                  }
                );
              }
              that.setData({
                pageDataList: that.data.pageDataList,
              });
            },
            fail: (res) => {},
          });
        } else {
          wx.showToast({
            title: "只能选择一块地图",
            icon: "error",
            duration: 2000,
          });
        }

        break;

      case "nameCard":
        userApi
          .getPersonalCard({
            userId: this.data.userId,
          })
          .then((res) => {
            if (res.code === 200 && res.data) {
              if (!insert) {
                this.data.pageDataList.push({
                  type: "nameCard",
                  content: res.data,
                });
                this.setData({
                  pageDataList: this.data.pageDataList,
                });
              } else {
                that.data.pageDataList.splice(
                  that.data.insertDir === "up"
                    ? that.data.insertIdx
                    : that.data.insertIdx + 1,
                  0,
                  {
                    type: "nameCard",
                    content: res.data,
                  }
                );
                this.setData({
                  pageDataList: this.data.pageDataList,
                });
              }
            } else {
              wx.showToast({
                title: "暂无数据",
                icon: "none",
                duration: 2000,
              });
            }
          });
        break;

      default:
        let textNum = 0;
        let dividerNum = 0;
        this.data.pageDataList.forEach((item) => {
          if (item.type === "text") {
            textNum++;
          }
          if (item.type === "divider") {
            dividerNum++;
          }
        });
        if (textNum >= 9 && type === "text") {
          wx.showToast({
            title: "最多选择九块文字！",
            icon: "none",
            duration: 2000,
          });
          break;
        }
        if (dividerNum >= 8 && type === "divider") {
          wx.showToast({
            title: "最多选择八条分割线！",
            icon: "none",
            duration: 2000,
          });
          break;
        }
        if (!insert) {
          this.data.pageDataList.push({
            type,
            content: "",
            key: this.data.editorKey,
            fontSize: 28,
            fontWeight: "normal",
          });
        } else {
          that.data.pageDataList.splice(
            that.data.insertDir === "up"
              ? that.data.insertIdx
              : that.data.insertIdx + 1,
            0,
            {
              type,
              content: "",
              key: this.data.editorKey,
              fontSize: 28,
              fontWeight: "normal",
            }
          );
        }
        this.setData({
          pageDataList: this.data.pageDataList,
        });
        break;
    }
    this.setData({
      showPopBack: false,
    });
  },
  deleteImg(e) {
    let idx = this.data.popImgIdx;
    let index = this.data.popItemIdx;
    let that = this;
    wx.showModal({
      title: "",
      content: "是否确认删除",
      success(res) {
        if (res.confirm) {
          that.data.pageDataList[index].content.splice(idx, 1);
          that.setData({
            pageDataList: that.data.pageDataList,
          });
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },
  clickImg(e) {
    let idx = e.currentTarget.dataset["idx"];
    let index = e.currentTarget.dataset["index"];
    this.setData({
      popImgIdx: idx,
      popItemIdx: index,
      popImgUrl: this.data.pageDataList[index].content[idx],
      showPopBack3: true,
    });
  },
  changeText(e) {
    let idx = e.currentTarget.dataset["idx"];
    this.data.pageDataList[idx].content = e.detail.value;
    this.setData({
      pageDataList: this.data.pageDataList,
    });
  },
  addImage(e) {
    let idx = e.currentTarget.dataset["idx"];
    let that = this;
    if (that.data.pageDataList[idx].content.length < 9) {
      wx.chooseMedia({
        count: 9 - that.data.pageDataList[idx].content.length,
        mediaType: "image",
        success: function (res) {
          res.tempFiles.forEach((item) => {
            that.data.pageDataList[idx].content.push(item.tempFilePath);
          });
          that.setData({
            pageDataList: that.data.pageDataList,
          });
        },
      });
    } else {
      wx.showToast({
        title: "超过选择上限！",
        icon: "error",
        duration: 2000,
      });
    }
  },
  deleteEditor(e) {
    let idx = e.currentTarget.dataset["idx"];
    this.data.pageDataList.splice(idx, 1);
    this.setData({
      pageDataList: this.data.pageDataList,
    });
  },
  move2top(e) {
    let idx = e.currentTarget.dataset["idx"];
    let temp = JSON.parse(JSON.stringify(this.data.pageDataList[idx]));
    this.data.pageDataList.splice(idx, 1);
    this.data.pageDataList.unshift(temp);
    this.setData({
      pageDataList: this.data.pageDataList,
    });
  },
  moveDown(e) {
    let idx = e.currentTarget.dataset["idx"];
    if (idx + 1 <= this.data.pageDataList.length) {
      let temp = JSON.parse(JSON.stringify(this.data.pageDataList[idx]));
      this.data.pageDataList[idx] = this.data.pageDataList[idx + 1];
      this.data.pageDataList[idx + 1] = temp;
      this.setData({
        pageDataList: this.data.pageDataList,
      });
    }
  },
  moveUp(e) {
    let idx = e.currentTarget.dataset["idx"];
    if (idx - 1 >= 0) {
      let temp = JSON.parse(JSON.stringify(this.data.pageDataList[idx]));
      this.data.pageDataList[idx] = this.data.pageDataList[idx - 1];
      this.data.pageDataList[idx - 1] = temp;
      this.setData({
        pageDataList: this.data.pageDataList,
      });
    }
  },
  insertEditor(e) {
    let idx = e.currentTarget.dataset["idx"];
    this.setData({
      showPopBack: true,
      insertIdx: idx,
    });
  },
  closePopBack() {
    this.setData({
      showPopBack: false,
    });
  },
  closePopBack3() {
    this.setData({
      showPopBack3: false,
    });
  },
  chooseDir(e) {
    let dir = e.currentTarget.dataset["dir"];
    this.setData({
      insertDir: dir,
    });
  },
  handleTextFontStyle(e) {
    let type = e.currentTarget.dataset["type"];
    let idx = e.currentTarget.dataset["idx"];
    switch (type) {
      case "fw":
        if (this.data.pageDataList[idx].fontWeight === "normal") {
          this.data.pageDataList[idx].fontWeight = "bold";
        } else {
          this.data.pageDataList[idx].fontWeight = "normal";
        }
        this.setData({
          pageDataList: this.data.pageDataList,
        });
        break;

      case "fzu":
        if (this.data.pageDataList[idx].fontSize < 84) {
          this.data.pageDataList[idx].fontSize =
            this.data.pageDataList[idx].fontSize + 2;
          this.setData({
            pageDataList: this.data.pageDataList,
          });
        }
        break;

      case "fzd":
        if (this.data.pageDataList[idx].fontSize > 16) {
          this.data.pageDataList[idx].fontSize =
            this.data.pageDataList[idx].fontSize - 2;
          this.setData({
            pageDataList: this.data.pageDataList,
          });
        }
        break;

      default:
        break;
    }
  },
});
